<?php

namespace app\data\service;

use app\data\model\ShopGoods;
use app\data\model\ShopGoodsCate;
use app\data\model\ShopGoodsItem;
use app\data\model\ShopGoodsMark;
use app\data\model\ShopGoodsStock;
use app\data\model\ShopOrder;
use app\data\model\ShopOrderQysDocument;
use Contract;
use think\admin\Service;
use Util;
use Category;
use DocumentAddByMultipleFileRequest;
use Dompdf\Dompdf;
use Dompdf\Options;
use Exception;
use Mpdf\Mpdf;
use Spatie\PdfToImage\Pdf;
use think\facade\App;
use think\facade\Log;
use think\helper\Arr;
use User,ContractPageRequest,Signatory,ContractDraftRequest,DocumentAddByFileRequest,ContractSendRequest,Stamper,DocumentDownloadRequest,ContractMiniappTicketRequest;

/**
 * 契约锁
 * Class QysService
 * @package app\data\service
 */
class QysService extends Service
{

    private static function getSDk(){
        require_once './vendor/sdk-php-3.6.1/com/qiyuesuo/Util.php';
        return  Util::getSDk();
    }
    /**
     * 
     */
    public static function mkQysSend($id='808'){
        //1.根据id 查询
        
        $order =  ShopOrder::field('*')->append(['type_text', 'matter_name'])->where('id', $id)->find()->toArray();
        //2.生成 契约锁草稿
        $draft_result =  self::mkDraft($order);
        if($draft_result[0]!=1){
            return $draft_result;
        }
        $contractId =   $draft_result[2]['result']['id'];
        //2.生成pdf
        $pdf_result = self::qysDocument($order,$contractId);//声明书
        if($pdf_result[0]!=1){
            return $pdf_result;
        }
    
        //3.契约锁行为  发起合同
        return  self::sendOrder( $order );
        
    }
    /**
     * 检测签约人数
     */
    public static function checkClientrNum($order){
        return  ShopOrder::field('*')->where('unified_numbering', $order['unified_numbering'])->select()->toArray();
    }

    /**
     * 发起合同
     */
    private static function sendOrder( $order){
        $order =  ShopOrder::field('*')->where('id', $order['id'])->find()->toArray();
        // $qys_result =  json_decode($order['qys_api_result']);

        $model = ShopOrderQysDocument::mk()->where(['contractId' => $order['contractId']]);
        $docunmentList = $model->order('id desc')->select()->toArray();
        $result = self::send( $docunmentList,  $order);
        if (isset($result['code']) &&  $result['code'] === 0) {
            return [1, 'success', $result, 0];
        } 
        return [0, '生成合同错误',  $result, 0];
    }   

    /**
     * 生成pdf并发送文档
     */
    private static function qysDocument($order,$contractId){
        $order =  ShopOrder::field('*')->where('id', $order['id'])->find()->toArray();
        //1.生成pdf
        $pdf_list = json_decode($order['qys_document_list']);
        // $pdf_list = self::mkLocalPdf($order);
        $agreement = self::getAgreement();
        foreach($pdf_list as $key=>$value){
            foreach($value as $k=>$v){
            //     $frist_name = explode('.', basename($v));
            //     $array_name = explode('_', $frist_name[0]);
               
                $file_path = app()->getRootPath() .'public'. parse_url($v, PHP_URL_PATH);
                $sk = $k; 
                if($k>50 && $k<60){
                    $sk = 50;
                }
                $result = self::addbyfile($contractId,$file_path,$agreement[$sk]);
                if (isset($result['code']) &&  $result['code'] === 0) {
                    //2.添加文档id记录数据库
                   $array = [];
                    $array['shop_id']= $order['id'];
                    $array['contractId']= $contractId;
                    $array['documentId']= $result['result']['documentId'];
                    $array['title']= $agreement[$sk];
                    $array['type_key']= $sk;
                    $array['file_path']=  $file_path;
                    $array['type_key2']= 0;
                    if($k>50 && $k<60){
                        $array['type_key2']= $k-50;
                    }
                    $data[] = $array;
                } else{
                    return [0, '上传文档错误', 0, 0];
                }

            }
        }
        ShopOrderQysDocument::mk()->insertAll($data);
        return [1, 'success', $result, 0];
    }

    /**
     * 生成合同草稿
     */
    private static function mkDraft($order){
        //1.发送请求
        $result = self::draft($order);
        if (isset($result['code']) &&  $result['code'] === 0) {
            //2.修改数据库
            ShopOrder::mk()->where(['id' => $order['id']])->update(
                ['contractId' => $result['result']['id'],
                 'qys_api_result' =>  json_encode($result['result'])
                ]
            );
            return [1, 'success', $result, 0];
        } 
        throw new Exception($result['message']);
        return [0, '生成草稿错误', 0, 0];
      
    }
    /**
     * 根据规则生成pdf
     */
    public static function mkPdf($html,$order,$key=''){
        if(!$html){
            return null;
        }
        $id = $order['contractId'];
        $array = explode('----分割----', $html);
        $data = [];
        if($key == 50){
            $client_num = count(self::checkClientrNum($order));
            if(count($array) != $client_num){
                throw new Exception('授权人数量和签约模版不匹配 请检查 "----分割----" 符号和模版数量 ');
            }
        }
        foreach($array as $k =>$v){
            $fontPath = './public';
            $mpdf = new Mpdf([
                'fontDir' => [  $fontPath ],
                'fontdata' => [
                    'simsuns' => [
                        'R' => 'fs_GB2312.ttf',
                    ],
                ],
            ]);
            $mpdf->WriteHTML($v);
            $filePath = './public/pdf/'.$id.'/';
            $fileName = $key.'_' . $id .'_'.$k. '.pdf';
            // 确保目录存在
            if (!is_dir($filePath)) {
                mkdir($filePath, 0755, true);
            }
            $mpdf->Output(  $filePath.$fileName , 'F');
            $data []= app()->getRootPath() .'public/pdf/'.$id.'/'.$fileName ; 
        }
        return $data;
       
        // //生成pdf
        // $options = new Options();
        // $options->set('isHtml5ParserEnabled', true);
        // $options->set('isRemoteEnabled', true);
        // $dompdf = new Dompdf($options);


        // // 添加自定义字体
           
        //     $fontPath = './vendor/dompdf/dompdf/lib/fonts/fs_GB2312.ttf';
      
        //     // // 定义字体映射
        //     $fontMetrics = $dompdf->getFontMetrics();
        //     $fontMetrics->registerFont([
        //         'family' => '仿宋_GB2312',
        //         'style' => 'normal',
        //         'weight' => 'normal'
        //     ],$fontPath);

        // $dompdf->loadHtml($html);
        // // 3. 设置纸张大小和方向
        // $dompdf->setPaper('A4', 'portrait'); // A4 纸张，纵向
        // // 4. 渲染 HTML 为 PDF
        // $dompdf->render();
        // // 5. 生成文件保存到服务器
        // $output = $dompdf->output(); // 获取渲染后的 PDF 内容
        // // 文件保存路径（可以根据项目实际路径修改）
        // $filePath = './public/pdf/';
        // $fileName = 'qys_' . date('YmdHis') . '.pdf';
        // // 确保目录存在
        // if (!is_dir($filePath)) {
        //     mkdir($filePath, 0755, true);
        // }
        // // 将文件保存到服务器
        // file_put_contents($filePath . $fileName, $output);

       
    }

     /**
     * 发起合同
     * 
     */
    public static function send(  $docunmentList,$order ){
        $sdkClient = self::getSDk();
        $contractSendRequest = new ContractSendRequest();
        $contractSendRequest->setContractId(   $order['contractId'] );
        // $contractSendRequest->setBizId("1111111");
        $stampers = array();
        // $other_document = [];
        // foreach($docunmentList  as $key=>$value){
        //    if( $value['type_key'] == 20){
        //         $value['type_key']= $value['type_key'] +100;
        //         $other_document = $value;
        //         array_push($docunmentList, $other_document);
        //    }
        // }
       
        /*\*个指定签署位置：坐标定位\*\*/
        foreach($docunmentList as $key=>$value){
            $casename = 'getSetTypeCase'.$value['type_key'];
            $qys_result =  json_decode($order['qys_api_result'],true);
            if($value['type_key'] == 50){
                foreach( $qys_result['signatories'] as $ks=>$vs){
                    $stamper2 = new Stamper();
                    $stamper2->setType('PERSONAL');
                    $stamper2->setDocumentId($value['documentId']);
                    $stamper2->setSignatoryId($vs['id']);
                    foreach (self::$casename() as $kk=>$vv){
                        $stamper2->$kk($vv);
                    }
                    $stamper2->setKeywordIndex($ks+1);
                    array_push($stampers, $stamper2);
                }
                // $stamper2 = new Stamper();
                // $stamper2->setType('PERSONAL');
                // $stamper2->setDocumentId($value['documentId']);
                // $stamper2->setSignatoryId($qys_result['signatories'][$value['type_key2']]['id']);
                // foreach (self::$casename() as $kk=>$vv){
                //     $stamper2->$kk($vv);
                // }
                // array_push($stampers, $stamper2);
            }else{
                foreach( self::checkClientrNum($order) as $k=>$v){
                    $stamper2 = new Stamper();
                    $stamper2->setType('PERSONAL');
                    $stamper2->setDocumentId($value['documentId']);
                    $stamper2->setSignatoryId($qys_result['signatories'][$k]['id']);
                    foreach (self::$casename() as $kk=>$vv){
                        if($kk == 'setOffsetX'){
                            if($k >=3){
                                $vv = $vv+(((int)$k-3)*0.16);
                            }else{
                                $vv = $vv+($k*0.16);
                            }
                        }
                        if($k >=3){
                            if($kk == 'setOffsetY'){
                                if($value['type_key'] == 50 || $value['type_key'] == 40){
                                    $vv = $vv+(-0.08);
                                }else{
                                    $vv = $vv+(-0.04);
                                }
                              
                            }
                        }
                        $stamper2->$kk($vv);
                    }
                    array_push($stampers, $stamper2);
                }
            }
            
            
        }
        Log::write($stampers,'info');
        $contractSendRequest->setStampers($stampers);
        $result = $sdkClient->service($contractSendRequest);
        Log::write($result,'info');
        return $result;
    }
    private static function getFileExtension($filePath) {
        // 获取文件的扩展名
        $info = pathinfo($filePath);
        return isset($info['extension']) ? $info['extension'] : null;  // 如果存在扩展名则返回，否则返回 null
    }
    
     /**
     * 用文件添加合同文档
     */
    public static function addbyfile($contractId,$file_path,$title){
        $sdkClient = self::getSDk();
        $documentAddByFileRequest = new DocumentAddByFileRequest();
        $documentAddByFileRequest->setContractId($contractId);
        // $documentAddByFileRequest->setBizId("1111111ligeshen");
        // $file_path = 'https://gz.gzrzvisa.com/upload/a4/xiulei.pdf';// "/Users/macpro/Desktop/test/img/ttt001.docx";
        // $file_path = iconv("UTF-8", "GBK", realpath($file_path));
        $file = new \CURLFile($file_path);
        $documentAddByFileRequest->setFile($file );
        $documentAddByFileRequest->setFileSuffix(self::getFileExtension($file_path));
        $documentAddByFileRequest->setTitle($title);

        $result = $sdkClient->service($documentAddByFileRequest);

   
        // $documentAddByFileRequest = new DocumentAddByMultipleFileRequest();
        // $documentAddByFileRequest->setContractId('3304463023787295306');
        // $file_path = 'https://gz.gzrzvisa.com/upload/a4/test0010.pdf';// "/Users/macpro/Desktop/test/img/ttt001.docx";
        // $file = new \CURLFile($file_path);
        // $documentAddByFileRequest->setTitle('添加文档12312123docs');
        // $documentAddByFileRequest->setFiles([$file]);
        // $result = $sdkClient->service($documentAddByFileRequest);
        // print_r($result);
        Log::write($result,'info');
        return $result;
        // return $result;
    }
    /**
     * 回调信息处理
     */

    public static function callBack($json){
        // $json = '{"tenantType":"PERSONAL","contractStatus":"SIGNING","tenantName":"李博","contact":"18740017747","contractId":"3305482756695343390","tenantId":"3304661603919737785","callbackType":"PERSONAL"}';
        // $json = '{"contractStatus":"COMPLETE","contractId":"3305482756695343390","callbackType":"COMPLETE"}';
        $json = $json['content'];
        $content = json_decode( $json,true);
        //2.查询订单 判断状态    //1.查询状态 订单流程状态(0已取消,1信息确认中,2信息有误,3待认证,4待视频取证,5认证通过,6认证失败,7审批人审核,8已完成)
        $order =  ShopOrder::field('*')->where('contractId', $content['contractId'])->find();
        if($order){
            $order =  $order->toArray();
            if($order['status']==3){
                $client_list = self::checkClientrNum($order);
                //个人签字
                if( $content['callbackType'] == 'PERSONAL' ){
                    foreach ($client_list as $k=>$v){
                        if($v['client_phone'] == $content['contact']){
                            //修改对应的状态
                            ShopOrder::mk()->where(['id' => $v['id']])->update(
                                ['qys_callback_status' => 1,
                                 'qys_callback_info' =>   $json
                                ]
                            );
                        }
                    }
                }
                //合同完成
                if( $content['callbackType'] == 'COMPLETE' ){
                            //修改对应的状态
                            $status = $order['video_forensics']==1 ? 4 :5;
                            ShopOrder::mk()->where(['contractId' => $content['contractId']])->update(
                                ['status' =>  $status]
                            );
                }
            }
           
        }
    }

    /**
     * 通过orderid 下载qyspdf
     */
    public static function downPdfByOrderId($order){
        // $order = $order->toArray();
        $filePath = app()->getRootPath() .'public/qyspdf/'. $order->contractId.'/';
        if (!is_dir($filePath)) {
            //不存在
            mkdir($filePath, 0755, true);
        }
        $model = ShopOrderQysDocument::mk()->where(['contractId' => $order->contractId]);
        $docunmentList = $model->order('id desc')->select()->toArray();
        $docunmentListPath = [];
        foreach($docunmentList as $key=>$value){
            $result = self::downPdfByContractId($filePath.$value['documentId'].'.pdf',$value['documentId']);
            if (isset($result['code']) &&  $result['code'] === 0) {
                $arr = [
                    'title'=> self::getAgreement()[$value['type_key']],
                    'filePath'=>'/'.'qyspdf/'. $order->contractId.'/'.$value['documentId'].'.pdf'
                ];
                $docunmentListPath[] =$arr ;
                // $iamge_res = self::mkPdfImage($filePath.$value['documentId'].'.pdf', $filePath.$value['documentId'].'.png');
            } else{
                return [0, '上传文档错误', 0, 0];
            }
            
        }
        return [1, 'success', $docunmentListPath, 0];
    }
    /**
     * 通过pdfmake img
     */
    private static function mkPdfImage($pdfPath,$outputImagePath ) {
        try {
            // 指定 PDF 文件路径
            // $pdfPath = 'example.pdf'; // 输入的 PDF 文件路径
            // $outputImagePath = 'output/output.jpg'; // 输出图片的路径
        
            // 创建 Pdf 对象
            $pdf = new Pdf($pdfPath);
        
            // 设置分辨率（DPI），提高输出图片的质量
            $pdf->setResolution(150);
            
            // 将 PDF 转换为图片并保存
            $pdf->saveImage($outputImagePath);

          
            return '';
            // echo "PDF 已成功转换为图片：<a href='$outputImagePath'>查看图片</a>";
        } catch (Exception $e) {
            return '错误: ' . $e->getMessage();
        }
    }

    /**
     * 下载契约锁pdf
     */
    private static function downPdfByContractId($filePath,$documentId){
        $sdkClient = self::getSDk();
        // $filePath = app()->getRootPath() .'public/qyspdf/';
        // $fileName =  'test.pdf';
        // // 确保目录存在
        // if (!is_dir($filePath)) {
        //     mkdir($filePath, 0755, true);
        // }
        $filePath = $filePath ;
        $documentDownloadRequest = new DocumentDownloadRequest($documentId);
        return $sdkClient->downloadService($documentDownloadRequest, $filePath);
        // print_r($result);
    }

    /**
     * 生成部署页面
     */
    public static function mkPageTicket($id){
        //1.查询状态 订单流程状态(0已取消,1信息确认中,2信息有误,3待认证,4待视频取证,5认证通过,6认证失败,7审批人审核,8已完成)
        $order =  ShopOrder::field('*')->where('id', $id)->find()->toArray();
        if($order['contractId']==0){
            return [1, 'success',  ['ticket'=> '', 'str'=>  '去认证'  ], 0];
        }
        if($order['status']==3){
            //2.查询是否需要 多不认证
            $client_list = self::checkClientrNum($order);
            foreach ($client_list as $key=>$value){
                if($value['qys_callback_status'] !=1){
                    $result = self::miniAppeXchange($value['client_phone'],$order['contractId']);
                    if (isset($result['code']) &&  $result['code'] === 0) {
                        $str = '去认证';
                        if(count($client_list)>1){
                            $str = '去认证 '.(string)($key).'/'.  (string)count($client_list) ;
                        }
                        $arr = [
                            'ticket'=> $result['result']['ticket'],
                            'str'=>  $str 

                        ];
                        return [1, 'success', $arr, 0];
                    }
                }
            }
        }
        return [1, 'success',  ['ticket'=> '', 'str'=>  '去认证'  ], 0];
      
        // $iphone = '18802447269';
        // $ContractId = '3305464913031377799';
        // $res = self::pageUrl($iphone,$ContractId);
        // var_dump($res);
    }

     /**
     * 生成合同签署令牌
     */
    private static function miniAppeXchange($iphone,$ContractId){
        $sdkClient = self::getSDk();
        $user = new User();
        // $user->setName('胡*坤');
        $user->setContact($iphone);
        $user->setContactType('MOBILE');
        $baseRequest = new ContractMiniappTicketRequest();
        $baseRequest->setContractId($ContractId);
        $baseRequest->setUser($user);
        $result = $sdkClient->service($baseRequest);
        // print_r($result);
        return $result;
    }
    /**
     * 部署页面
     */
    private static function pageUrl($iphone,$ContractId){
        $sdkClient = self::getSDk();
        $contractPageRequest = new ContractPageRequest();
        $contractPageRequest->setContractId($ContractId);
        // $contractPageRequest->setBizId("123456789");
        $user = new User();
        $user->setContact($iphone);
        $user->setContactType("MOBILE");
        $contractPageRequest->setUser($user);
        $result = $sdkClient->service($contractPageRequest);
        return $result;
    }

    /**
     * 创建合同草稿	
     */
    public static function draft($order){
        $sdkClient = self::getSDk();
        /**  合同基本信息 */
        $contract = new Contract();
        //        $contract->setId("");
        // $contract->setBizId("1111111ligeshen");
        $contract->setSubject($order['type_text']);
        // $contract->setDescription("合同描述");
        // $contract->setSn("123321");
        // $contract->setExpireTime("2024-12-25 00:00:00");
        $contract->setOrdinal(true);
        $contract->setSend(false);
        
        
        /*\*指定业务分类\*\*/
        $category = new Category();
        $category->setId("3304363348921008420");
        $contract->setCategory($category);
        // $creator = new User();
        // $creator->setContact("18740017747");
        // $creator->setContactType("MOBILE");
        // $contract->setCreator($creator);

        //添加签约人 
        $signatories = array();
        foreach( self::checkClientrNum($order) as $key=>$value){
            $personalSignatory = new Signatory();
            $personalSignatory->setTenantType("PERSONAL");
            $personalSignatory->setTenantName($value['client_name']);
            $personalSignatory->setSerialNo(2);
            $receiver = new User();
            $receiver->setContact($value['client_phone']);
            $receiver->setContactType("MOBILE");
            $personalSignatory->setReceiver($receiver);
            array_push($signatories, $personalSignatory);
        }
        $contract->setSignatories($signatories);
        Log::write($signatories,'info');

        $baseRequest = new ContractDraftRequest($contract);
        $result = $sdkClient->service($baseRequest);
        Log::write($result,'info');
        return $result;
    }
    
    private static function getAgreement(){
        return  [
            '10'=>'声明书',
            '20'=>'谈话笔录',
            '30'=>'公证告知书',
            '40'=>'公证受理通知单',
            '50'=>'公证申请表',
            '60'=>'委托书',
        ];
    }   
    
    public static function mkDbDocumentList($data){
        $files = [
            'proxy_statement_pdf' =>'10',
            'read_agreement2_pdf' =>'20',
            'read_agreement3_pdf' =>'30',
            'read_agreement4_pdf' =>'40',
            'read_agreement5_0_pdf' =>'50',
            'read_agreement5_1_pdf' =>'51',
            'read_agreement5_2_pdf' =>'52',
            'read_agreement5_3_pdf' =>'53'
        ];
        $result = [];
        foreach($files as $key=>$value){
            $input  = input($key);
            if($input != null){
                if($key == 'proxy_statement_pdf'){
                    if($data['proxy_type']==0){
                        $value = 60;
                    }
                }
                $result[] = array(
                    $value=>$input
                );
            }
           

        }
        return json_encode($result);

    }

    /**
     * 生成本地pdf
     */
    private static function mkLocalPdf($order){
       

        $pdf_list = [];
        if($order['proxy_type']==1){
            array_push($pdf_list,self::mkPdf($order['proxy_statement'], $order ,'10')); ; //声明书
        }else{
            array_push($pdf_list,self::mkPdf($order['proxy_statement'], $order ,'60')); ; //委托书
        }
        array_push($pdf_list,self::mkPdf($order['read_agreement2'], $order ,'20')); ; //声明书
        array_push($pdf_list,self::mkPdf($order['read_agreement3'], $order ,'30')); ; //声明书
        array_push($pdf_list,self::mkPdf($order['read_agreement4'], $order ,'40')); ; //声明书
        array_push($pdf_list,self::mkPdf($order['read_agreement5'], $order ,'50')); ; //声明书
        return array_filter($pdf_list);
    }


     /**
     * 获取type 50 公证申请表' 索引位置信息
     */
    private static function getSetTypeCase50(){
        return  [
            'setKeyword' =>'签名',
            // 'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' => 0.1,
            // 'setOffsetY' => -0.01,

        ];
    }
    /**
     * 获取type 40 公证受理通知单 索引位置信息
     */
    private static function getSetTypeCase40(){
        return  [
            'setKeyword' =>'申请人签名',
            // 'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' => 0.1,
            'setOffsetY' => -0.02,

        ];
    }
     /**
     * 获取type 30 公证告知书 索引位置信息
     */
    private static function getSetTypeCase30(){
        return  [
            'setKeyword' =>'申请人签名',
            // 'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' =>0.02,
            'setOffsetY' => -0.02,

        ];
    }
     /**
     * 获取type 20 谈话笔录 索引位置信息
     */
    private static function getSetTypeCase20(){
        return  [
            'setKeyword' =>"申请人签名",
            'setPage' => 0,
            'setKeywordIndex' => 0,
            'setWidth'=> 32,
            'setOffsetX' => 0.01,
            'setOffsetY' => -0.02,

        ];
    }

    /**
     * 获取type 120 谈话笔录  申请人签名 索引位置信息
     */
    private static function getSetTypeCase120(){
        return  [
            'setKeyword' =>"申请人签名",
            'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' => 0,
            'setOffsetY' => -0.02,

        ];
    }


    /**
     * 获取type 10 生命树 索引位置信息
     */
    private static function getSetTypeCase10(){
        return  [
            'setKeyword' =>'声明人签字',
            // 'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' => 0.02,
            'setOffsetY' => -0.02,
            // 'setOffsetY' => -1,

        ];
    }
    /**
     * 获取type 60 委托书 索引位置信息
     */
    private static function getSetTypeCase60(){
        return  [
            'setKeyword' =>'委托人签字',
            // 'setPage' => 0,
            'setKeywordIndex' => 0,
            'setOffsetX' => 0.02,
            'setOffsetY' => -0.02,

        ];
    }
   
}